<?php

/**
 * 营养方案
 * */
class YingYangService {
    /**
     * 获取金字塔
     */
    public  function getPramid()
    {
        
    }
    /**
     * 获取饮食建议
     */
    public function getAdvice($arr,$disevaluate = null)
    {
        if(is_array($arr)){
            if(!isset($arr["uid"])){
                return JSONHelper::ERROR_ILLEGAL_REQUEST;
            }
            $userinfo = EvaluateUserDiselement::model()->findByAttributes(array(
                    "uid"=>$arr["uid"],),array("order"=>"id desc"));
        }elseif($arr instanceof EvaluateUserDiselement){
            $userinfo = $arr;
        }else{
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        
        if($userinfo === null){
            return JSONHelper::ERROR_EVALUATE_NOINFO;
        }
        $dis = null;
        if($disevaluate !== null){
            foreach ($disevaluate["items"] as $key => $it) {
                $value = $it["value"];
                if($value["percent"]>=$value["high"]){
                    $dis[$it["id"]] = 1;
                }
            }
        }
        $items = array();
        if($userinfo->hypertension_history||isset($dis[Disease::GAOXUEYA])){
            $items[] = "高血压";
        }
        if($userinfo->diabetes_history||isset($dis[Disease::TANGNIAOBING])){
            $items[] = "糖尿病";
        }
        if($userinfo->coronary_history||isset($dis[Disease::GUANXINBING])){
            $items[] = "冠心病";
        }
        if($userinfo->hyperlipidemia_history){
            $items[] = "高脂血症";
        }
        $ret=EvaluateYingyangSuggest::model()->findAllByAttributes(array("tags"=>$items));
        $rets = array();
        foreach($ret as $it){
            $item["name"] = $it->tags;
            $item["advice"] = $it->suggest;
            array_push($rets, $item);
        }
        return $rets;
    }
    /**
     * 获取推荐食物，只针对高风险疾病
     */
    public function getRecFood($dis)
    {
        if($dis == null){
            return array();
        }
        $items = array();
        if(is_string($dis)){
            $dis = array($dis);
        }
        
        if(is_array($dis)){
            foreach($dis as $it){
                $ret = EvaluateFood::model()->getRecFoods($it);
                if($ret === false){
                    return JSONHelper::ERROR_ILLEGAL_DATA;
                }
                foreach ($ret as $i) {
                    $item["name"] = $i->name;
                    $item["image_url"] = ($i->image_url == null)?"images/app/food/".$i->name.".png":$i->image_url;
                    if(!isset($items[$it])){
                        $items[$it] = array();
                    }
                    array_push($items[$it], $item);
                }
            }
        }else{
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        return $items;
    }
    
    public function getForbidFood($dis,$arr = array())
    {
        if($dis == null){
            return array();
        }
        if(is_string($dis)){
            $dis = array($dis);
        }
        $forbidfood = array();
        
        
        
        foreach($dis as $it){
            $ret = EvaluateDiseaseType::model()->findByAttributes(array("name"=>$it));
            if($ret === null){
                return false;
            }
            $forbidfood = array_merge($forbidfood,explode(";", $ret->forbid));
        }
        $forbidfood = array_unique($forbidfood);
        $unfood = array();
        if (isset($arr["uid"])) {
            $arr = B2bUserQuestionResult::model()->findAllByAttributes(array("uid" => $arr["uid"],
                        "type"=>array("salt_food","drink","smoking")));
            if (count($arr) == 0) {
                return false;
            }
            foreach ($arr as $it) {
                switch ($it->type) {
                    case "salt_food":
                        if($it->value){
                            array_push($unfood, "忌多盐");
                        }
                        break;
                    case "drink":
                        if($it->value){
                            array_push($unfood, "忌酒");
                        }
                        break;
                    case "smoking":
                        if($it->value){
                            array_push($unfood, "忌烟");
                        }
                        break;
                    default:
                        break;
                }
                    
            }
        }
        $forbidfood = array_diff($forbidfood,$unfood);
        return array("unfood"=>$unfood,"forbidfood"=>$forbidfood);
    }

    /**
     * 得到疾病结果的解析页面数据
     * $user
     * @param unknown_type $disid
     * @param unknown_type $user
     */
    public function getSummary($userid) {
        //$user = array('id' => 2, 'username' => 'test')
        //		if(!isset($_GET["uid"])||!isset($_GET["disid"])){
        //			echo '非法请求';
        //			return;
        //		}
        //		$userid = $_GET["uid"];
        //get the top of the
        /* 1 	get the disease_element ret
         * 		select * from ** where suggest = 1;
         *
         * 2 	"content" => group the description array_implode(ret->name,',')
         * 		integrate the ret by array("type" => ret->description,"result" => 0/1, "content" => string[ret->name], "name" => ret-field_name)
         * 		array("家族史" => array("1",'高血压*&^*'))
         */
        $dis_ele_ins = new EvaluateDiseaseElement();
        $summarysuggestion_ins = $dis_ele_ins->getSummarySuggestion();
        $user_info = EvaluateExaminationBasic::model()->findByAttributes(array("uid" => $userid));
        $summary_ret = array();
        foreach ($summarysuggestion_ins as $it) {
            $column = $it->field_name;
            if (!isset($summary_ret[$it->description])) {
                if ($user_info->$column == 1) {
                    $summary_ret[$it->description] = array("result" => 1, "content" => $it->name);
                } else {
                    $summary_ret[$it->description] = array("result" => 0, "content" => "-");
                }
            } else {
                if ($user_info->$column == 1 && $summary_ret[$it->description]["result"] == 1) {
                    $summary_ret[$it->description]['content'].=',' . $it->name;
                }
                if ($user_info->$column == 1 && $summary_ret[$it->description]["result"] == 0) {
                    $summary_ret[$it->description] = array("result" => 1, "content" => $it->name);
                }
            }
        }


        //get the center of the page
        /* instance a disease
         * 1 	for ( i = 1; i< 5; i++){
         * 		$dis = new Disease(i);
         * 		$ret = $dis->assess($userid);
         * 2	save level
         * 		if ($ret->value > $ret->int_med_val_high)
         * 			$value = '高';
         * 		if ($ret->value > $ret->int_med_val_low)
         * 			$value = '中';
         * 		else
         * 			$value = '低';
         *
         * 3	save advice
         * 		$disease_ins = disease_type($disid);
         * 		if (strpos($human_health_tag_ins->summary, $disease_ins->name."+".$vlaue) == false){
         * 			$human_health_tag_ins->summary = $human_health_tag_ins.$disease_ins->name."+".$vlaue;
         * 		}
         * 			$resolve = $dis->getAdvice($uid);
         * }
         *
         * array('resolve' => , 'summary' => )
         */
        $dis_summary = array();
        for ($i = 1; $i < 5; $i++) {
            $dis = new Disease($i);
            $disease_ins = EvaluateDiseaseType::model()->findByPk($i);
            $hum_health_ins = EvaluateHumanHealthTag::model()->findByAttributes(array("uid" => $userid));
            if (empty($hum_health_ins)) {
                $hum_ins = new EvaluateHumanHealthTag();
                $hum_ins->achieveAInstance($userid);
                $hum_health_ins = EvaluateHumanHealthTag::model()->findByAttributes(array("uid" => $userid));
            }
            if (empty($hum_health_ins->summary) || (strpos($hum_health_ins->summary, $disease_ins->name) === false)) {
                $ret = $dis->assess($userid);
                if ($ret['value'] > $ret['int_med_val_high']) {
                    $value = "高";
                }
                if ($ret['value'] > $ret['int_med_val_low']) {
                    $value = "中";
                } else {
                    $value = "低";
                }

                if (empty($hum_health_ins->summary)) {
                    $hum_health_ins->summary = $disease_ins->name . "+" . $value;
                } else {
                    $hum_health_ins->summary .= ',' . $disease_ins->name . "+" . $value;
                }
                $hum_health_ins->save();
            } else {
                $pos = strpos($hum_health_ins->summary, $disease_ins->name . "+");
                $size = strlen($disease_ins->name . "+");
                $pos += $size;
                $value = substr($hum_health_ins->summary, $pos, 3);
            }
            //			$resolve = $dis->getAdvice($userid);
            $resolve = $disease_ins->outline;
            array_push($dis_summary, array("disname" => $disease_ins->name, "dislevel" => $value, "resolve" => $resolve));
        }
        //		var_dump($dis_summary);exit();
        return array("dis_summary" => $dis_summary, "summary_ret" => $summary_ret);
        //		echo "<pre>";var_dump($dis_summary[1]);echo "</pre>";exit();
    }

    /**
     * 得到疾病以及未来发病率
     * get future diseaes probabilities
     * array("now_info" =>
     * 		 "future_info" =>)
     *
     */
    public function getDiseaseProbabilities($uid, $future) {
        $dis_pro_perc_arr = array();
        $now_per_arr = array();
        $future_per_arr = array();

        for ($i = 1; $i < 5; $i++) {
            $dis = new Disease($i);
            $now_level = "green";
            $future_level = 0;
            $now_ret = $dis->assess($uid);
            $future_ret = $dis->assess($uid, $future);
            $dis_ret = EvaluateDiseaseType::model()->findByPk($i);

            if ($now_ret['value'] < $now_ret['int_med_val_low']) {
                $now_level = "green";
            }
            if ($now_ret['int_med_val_low'] < $now_ret['value'] && $now_ret['value'] < $now_ret['int_med_val_high']) {
                $now_level = "yellow";
            }
            if ($now_ret['value'] > $now_ret['int_med_val_high']) {
                $now_level = "red";
            }

            if ($future_ret['value'] < $future_ret['int_med_val_low']) {
                $future_level = "green";
            }
            if ($future_ret['int_med_val_low'] < $future_ret['value'] && $future_ret['value'] < $future_ret['int_med_val_high']) {
                $future_level = "yellow";
            }
            if ($future_ret['value'] > $future_ret['int_med_val_high']) {
                $future_level = "red";
            }

            $now_per_arr["$dis_ret->name"] = array("now_per_ret" => $now_ret, "now_level" => $now_level, "description" => $dis_ret->description);
            $future_per_arr["$dis_ret->name"] = array("future_per_ret" => $future_ret, "futrue_level" => $future_level, "description" => $dis_ret->description);
        }

        $dis_pro_perc_arr = array("now_info" => $now_per_arr, "future_info" => $future_per_arr);

        return $dis_pro_perc_arr;
    }

    public function getDiseaseLevel($uid, $future) {
        $dis_pro_perc_arr = array();
        $now_per_arr = array();
        $future_per_arr = array();

        for ($i = 1; $i < 5; $i++) {
            $dis = new Disease($i);
            $now_level = "dw";
            $future_level = "dw";
            $now_ret = $dis->assess($uid);
            $future_ret = $dis->assess($uid, $future);
            $dis_ret = EvaluateDiseaseType::model()->findByPk($i);
            $step_now = 2;
            $step_future = 2;

            if ($now_ret['value'] < $now_ret['int_med_val_low']) {
                $now_level = "dw";
                $step_now = $this->calculateStepFac($now_ret, $now_level);
            }
            if ($now_ret['int_med_val_low'] < $now_ret['value'] && $now_ret['value'] < $now_ret['int_med_val_high']) {
                $now_level = "zw";
                $step_now = $this->calculateStepFac($now_ret, $now_level);
            }
            if ($now_ret['value'] > $now_ret['int_med_val_high']) {
                $now_level = "gw";
                $step_now = $this->calculateStepFac($now_ret, $now_level);
            }

            if ($future_ret['value'] < $future_ret['int_med_val_low']) {
                $future_level = "dw";
                $step_future = $this->calculateStepFac($future_ret, $future_level);
            }
            if ($future_ret['int_med_val_low'] < $future_ret['value'] && $future_ret['value'] < $future_ret['int_med_val_high']) {
                $future_level = "zw";
                $step_future = $this->calculateStepFac($future_ret, $future_level);
            }
            if ($future_ret['value'] > $future_ret['int_med_val_high']) {
                $future_level = "gw";
                $step_future = $this->calculateStepFac($future_ret, $future_level);
            }

            $now_per_arr["$dis_ret->name"] = array("now_per_ret" => $now_ret, "now_level" => $now_level, "description" => $dis_ret->description, "step" => $step_now);
            $future_per_arr["$dis_ret->name"] = array("future_per_ret" => $future_ret, "futrue_level" => $future_level, "description" => $dis_ret->description, "step" => $step_future);
        }

        $dis_pro_perc_arr = array("now_info" => $now_per_arr, "future_info" => $future_per_arr);
//var_dump($dis_pro_perc_arr);exit();
        return $dis_pro_perc_arr;
    }

    private function calculateStepFac($now_ret, $type) {
        $step = 0;
        if ($type == "dw") {
            $step = $this->calculateStep($now_ret['value'], $now_ret['int_med_val_low']);
        }
        if ($type == "zw") {
            $step = $this->calculateStep($now_ret['value'] - $now_ret['int_med_val_low'], $now_ret['int_med_val_high'] - $now_ret['int_med_val_low'], 4);
        }
        if ($type == "gw") {
            $step = $this->calculateStep($now_ret['value'] - $now_ret['int_med_val_high'], $now_ret['ceil'] - $now_ret['int_med_val_high'], 6);
        }
        return $step;
    }

    private function calculateStep($numerator, $denominator, $initailstep = 2) {
        $num = 1;
        if (($numerator / $denominator) > 0.5) {
            $num = 2;
        }
        $initailstep += $num;
        return $initailstep;
    }

    public function actionRisk($disid, $userid) {
        //		$disid = $_GET["disid"];
        //		$userid = $_GET["uid"];

        $dis_pro_perc_arr = $this->getDiseaseProbabilities($userid, 30);
        //		echo "<pre>";var_dump($dis_pro_perc_arr);exit();echo "</pre>";
        return array("dis_pro_perc" => $dis_pro_perc_arr);
    }

    /* 保存体质
     * 1 colculate A score except mild
     * 1.1	if(score < 30 ){}
     * 1.2	if(30<=score<40){insert into hum_constitution->tendency.=A}
     * 1.3	if(score>=40){insert into hum_constitution->belong.=A}
     *
     * 2 colculate mild score
     * 2.1	if(A.score >= 60 && empty(hum_constitution->belong)){insert into hum_constitution->belong = mild}
     */

    public function actionSaveConstitution($uid) {
        //		$uid = $_GET['uid'];
        $biased_arr = array("yangxuscore", "yinxuscore", "qixuscore", "tanshiscore", "shirescore", "xueyuscore", "tebingscore", "qiyuscore");
        $biased_cn_arr = array("阳虚体质", "阴虚体质", "气虚体质", "痰湿体质", "湿热体质", "血瘀体质", "特禀体质", "气郁体质");
        $hum_consitution_ret = EvaluateHumConstitution::model()->findAllByAttributes(array("uid" => $uid));
        $hum_consitution_ret = $hum_consitution_ret[0];
        $hum_consitution_ret->belongto = '';
        $hum_consitution_ret->tendency = '';
        $hum_consitution_ret->save();
        //		echo "<pre>";var_dump($hum_consitution_ret[0]->yangxuscore);echo "</pre>";exit();
        foreach ($biased_arr as $key => $value) {
            if (30 <= $hum_consitution_ret->$value && $hum_consitution_ret->$value < 40) {
                if (!empty($hum_consitution_ret->tendency)) {
                    $hum_consitution_ret->tendency .= "," . $biased_cn_arr[$key];
                } else {
                    $hum_consitution_ret->tendency = $biased_cn_arr[$key];
                }
                $hum_consitution_ret->save();
            }
            if ($hum_consitution_ret->$value >= 40) {
                if (!empty($hum_consitution_ret->belongto)) {
                    $hum_consitution_ret->belongto .= "," . $biased_cn_arr[$key];
                } else {
                    $hum_consitution_ret->belongto = $biased_cn_arr[$key];
                }
                $hum_consitution_ret->save();
            }
        }
        if ($hum_consitution_ret->mildscore >= 60 && empty($hum_consitution_ret->belongto)) {
            $hum_consitution_ret->belongto = "平和体质";
            $hum_consitution_ret->save();
        }
    }

    /**
     * 得到体质详细信息
     * Enter description here ...
     */
    public function getConstitution($uid) {
        //		$uid = $_GET['uid'];
        $constitution_detail_ret = '';
        $humconstitution_ret = EvaluateHumConstitution::model()->findByAttributes(array("uid" => $uid));
        $belongto = '平和体质';

        if (strpos($humconstitution_ret->belongto, $belongto) !== false) {
            //			echo "1";exit();
            $constitution_detail_ret = EvaluateContitutionDetail::model()->findByAttributes(array("name" => $belongto));
            //		echo "<pre>";var_dump($constitution_detail_ret);echo "</pre>";exit();
        } else {
            //			echo "2";exit();
            $belongto_arr = explode(",", $humconstitution_ret->belongto);
            $belongto = $belongto_arr[0];
            $constitution_detail_ret = EvaluateContitutionDetail::model()->findByAttributes(array("name" => $belongto));
        }
        //		echo "<pre>";var_dump($constitution_detail_ret);echo "</pre>";exit();
        return array("belongto_detail" => $constitution_detail_ret, "tendency" => $humconstitution_ret->tendency);
    }

    /**
     * 问卷计算出体质分数
     * $_get[constitution][tizhi][num]
     * $_get['constitution']
     *
     */
    public function setConstitution($constitution_arr) {
        //		$constitution_arr = $_GET['constitution'];
        foreach ($constitution as $tizhi) {
            $this->colculateConstitutionScore($tizhi);
        }
    }

    /* 计算体质方法
     * $type is a array('0' => score, '1' => score,...)
     * $score is a int
     *
     */

    private function colculateConstitutionScore($type) {
        $score = 0;
        foreach ($type as $key => $it) {
            $score+=$it;
        }
        $score = (($score - sizeof($type)) / (sizeof($type) * 4)) * 100;
        return $score;
    }

    /**
     * 获取人的总能量值,计算模型来自李博士
     */
    public function colculateEnergy($birthday,$gender,$weight,$height) {
        //男性：KK=66.5+[13.75×体重（千克）]+[5×身高（厘米）]-6.75×年龄+250*T
        //女性：KK=65.5+[9.56×体重（千克）]+[1.85×身高（厘米）]-4.67×年龄+220*T

        $energy = 1900;
        //$coefficient = array("男" => 1.78, "女" => 1.64);
        $birthday = date_create($birthday);
        $age = date_diff(date_create(), $birthday);
        $t = 1.2;

        if ($gender == JSONHelper::MAN) {
            $energy = 65.5 + 13.75 * $weight + 5 * $height - 6.75 * $age->y + 250 * $t;
        }else{
            //女性：KK=65.5+[9.56×体重（千克）]+[1.85×身高（厘米）]-4.67×年龄+220*T
            $energy = 65.5 + 9.56 * $weight + 1.85 * $height - 4.67 * $age->y + 220 * $t;
        }
        
        return $energy;
    }
    public function getMealCollocation($arr){
        //如果是传的uid，则查找所有信息
        $items = array();
        if (is_array($arr)&&isset($arr["uid"])) {
            try {
                $arr = B2bUserQuestionResult::model()->findAllByAttributes(array("uid"=>$arr["uid"]));
                if(count($arr) == 0){
                    return false;
                }
                foreach($arr as $it){
                    $items[$it->type] = $it->value;
                }
            } catch (Exception $e) {
                return false;
            }
        }else{
            $items = $arr;
        }
        if(!isset($items["age"])||!isset($items["weight"])||!isset($items["height"])
                ||!isset($items["gender"])){
            return JSONHelper::ERROR_EVALUATE_NOINFO;
        }
        
        $ret = $this->getMealCollocationByElement($items["age"],$items["gender"],$items["weight"],$items["height"]);
        return $ret;
    }
    /**
     * 获取食谱，大类别的能量（千卡）跟质量（g）
     */
    public function getMealCollocationByElement($birthday,$gender,$weight,$height) {
        
        $meal_ret = EvaluateMealCollocation::model()->findAll();

        $energy = $this->colculateEnergy($birthday,$gender,$weight,$height);
        $meal_arr = array();
        $energy_arr = array();
        $mass_arr = array();
        $mass = 0;
        $meal_energy_percent = array("早" => 30, "中" => 35, "晚" => 25, "加餐" => 10);

        foreach ($meal_ret as $ret) {
            if ($ret->mealtype != "其他") {
                $energy_needed = ($energy * $meal_energy_percent[$ret->mealtype]) / 100;
                $energy_needed = ($energy_needed * $ret->coefficient) / 100;
                if (isset($energy_arr[$ret->type])) {
                    $energy_arr[$ret->type] += $energy_needed;
                } else {
                    if ($ret->type !== null) {
                        $energy_arr[$ret->type] = 0;
                        $energy_arr[$ret->type] += $energy_needed;
                    }
                }

                $energy_per_kilo_arr = explode("/", $ret->energyperkilogram);
                $energy_per_unit = $energy_per_kilo_arr[0];
                $unit_arr = explode("*", $energy_per_kilo_arr[1]);
                $mass = (int) ($energy_needed / $energy_per_unit + 0.5) * $unit_arr[0];
                $meal_arr[$ret->mealtype][$ret->name] = array("mass" => $mass . $unit_arr[1], "energy" => $energy_needed);
            }
            if ($ret->mealtype == "其他") {
                $energy_per_unit = explode("*", $ret->energyperkilogram);
                $unit_arr = explode("*", $energy_per_kilo_arr[1]);
                $mass = (int) ($energy_per_unit[0] + 0.5);
                $meal_arr[$ret->mealtype][$ret->name] = array("mass" => $mass . $energy_per_unit[1], "energy" => "-");
            }

            if (isset($mass_arr[$ret->type])) {
                $mass_arr[$ret->type] += $mass;
            } else {
                if ($ret->type !== null) {
                    $mass_arr[$ret->type] = 0;
                    $mass_arr[$ret->type] += $mass;
                }
            }
        }
        //var_dump(array("meal_arr" => $meal_arr, "energy_arr" => $energy_arr, "mass_arr" => $mass_arr));
        $result["total"] = $energy;
        $result["meal"] = $meal_arr;
        return $result; 
        //return array("meal_arr" => $meal_arr, "energy_arr" => $energy_arr, "mass_arr" => $mass_arr);
    }

    private function getDisType($disid) {
        $type = "";
        switch ($disid) {
            case 1:
                $type = "高血压";
                break;
            case 2:
                $type = "冠心病";
                break;
            case 3:
                $type = "脑卒中";
                break;
            case 4:
                $type = "糖尿病";
                break;
            default:
                $type = "未知";
                break;
        }
        return $type;
    }

    /**
     * 营养方案
     */
    public function actionNutritionlist() {
        $result = $this->diseaseService->getNutritionList($_GET);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /**
     * 营养方案项目详情
     */
    public function actionNutritionItem() {
        $result = $this->diseaseService->getNutritionItem($_GET);
        if (is_int($result)) {
            echo "错误的请求";
            return;
        }
        $this->render("nutrition_item", array("item" => $result));
    }

    /**
     * return to the index page from result page
     * Enter description here ...
     */
    public function actionListOut() {
        $result = $this->diseaseService->getList();

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /**
     * remove the old question answer,
     * Enter description here ...
     */
    public function questionAgain() {
        if (isset($_GET['uid'])) {
            $userid = $_GET['uid'];
        } else {
            return 0;
        }
        if (isset($_GET['disid'])) {
            $disid = $_GET['disid'];
        } else {
            return 0;
        }

        $ret = Disease::deleteUserInfo($userid, $disid);
    }

}

?>
